<template>
  <a-breadcrumb class="app-breadcrumb">
    <transition-group name="breadcrumb">
      <a-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
        <span v-if="item.redirect === 'undefined' || index == levelList.length - 1" class="now-redirect">
          {{ item.meta.title }}
        </span>
        <a class="history-redirect" v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
      </a-breadcrumb-item>
    </transition-group>
  </a-breadcrumb>
</template>

<script setup lang="ts">
import {watch, ref, onMounted} from "vue";
import {useRoute, useRouter} from "vue-router";

const emit = defineEmits(['message-to-parent']);
const route = useRoute();
const router = useRouter();
let levelList = ref<any>();
const firstPageInfo: any = ref()

onMounted(() => {
  let matched: any = route.matched.filter((item) => item.meta && item.meta.title);
  firstPageInfo.value = matched[0];
  getBreadcrumb()
})

function isDashboard(route: any) {
  const path = route && route.path;
  if (!path) {
    return false;
  }
  return path.trim().toLocaleLowerCase() === firstPageInfo.value.path.toLocaleLowerCase();
}

function getBreadcrumb() {
  let matched: any = route.matched.filter((item) => item.meta && item.meta.title);
  const first = matched[0];
  if (!isDashboard(first)) {
    matched = [{path: firstPageInfo.value.path, meta: firstPageInfo.value.meta}].concat(matched);
  }
  levelList.value = matched.filter((item: any) => item.meta && item.meta.title);
}

function handleLink(item: { redirect: any; path: any, children: any }) {
  const {path} = item;
  router.push(path);
  emit('message-to-parent', path);
}

watch(route, (_newVal, _oldVal) => {
  getBreadcrumb();
});
</script>

<style lang="scss" scoped>
@use "@/styles/variables" as *;

.app-breadcrumb {
  display: inline-block;
  font-size: 16px;
  line-height: $breadcrumbHeight;
  padding: 8px;
  width: 100%;
  position: relative;
  background-color: $breadcrumbBg;

  .now-redirect {
    color: $breadcrumbActiveText;
    font-weight: 700;
    cursor: text;
  }

  .history-redirect {
    color: $breadcrumbText;
    cursor: pointer;
  }
}

.ant-breadcrumb a {
  height: 100%;
}

:deep(.ant-breadcrumb), :deep(.ant-breadcrumb-separator) {
  color: $breadcrumbText;
}
</style>
